﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc.Filters;
using SheepStorage.Domain.DTO.Output;
using SheepStorage.Domain.Entity;
using SheepStorage.Repository.Interface;
using SheepStorage.Service.Interface;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace SheepStorage.Service.DataImp
{
	/// <summary>
	/// 羊只转舍服务层
	/// </summary>
	public class ChangeDormitoryService: IChangeDormitoryService
	{
		/// <summary>
		/// 羊只转舍数据仓库
		/// </summary>
		private readonly IBaseRepository<SheepChangeDormitory> ChangeDormitorybaseRepository;
		/// <summary>
		/// 羊只档案数据仓库
		/// </summary>

        private readonly IBaseRepository<SheepRecord> SheepRecordbaseRepository;

        private readonly IBaseRepository<BuildingManagement> BuildingbaseRepository;

        private readonly IBaseRepository<SheepField> SheepFieldbaseRepository;

        private readonly IMapper mapper;
		//构造函数
		public ChangeDormitoryService(IBaseRepository<SheepChangeDormitory> ChangeDormitorybaseRepository, IMapper mapper, IBaseRepository<SheepRecord> SheepRecordbaseRepository, IBaseRepository<BuildingManagement> BuildingbaseRepository, IBaseRepository<SheepField> SheepFieldbaseRepository)
		{
			this.ChangeDormitorybaseRepository = ChangeDormitorybaseRepository;
			this.SheepRecordbaseRepository = SheepRecordbaseRepository;
			this.BuildingbaseRepository = BuildingbaseRepository;
			this.SheepFieldbaseRepository = SheepFieldbaseRepository;
            this.mapper = mapper;
		}



		/// <summary>
		/// 显示羊只转舍列表 
		/// </summary>
		/// <returns></returns>
		public async Task<PageOutput<SheepChangeDormitoryOutput>> GetChangeDormitories(string startDate,string endDate,string OverBit,int ChangedormitoryType,string outDrom,string outField,int inDrom,int inField,int pageIndex,int pageSize)
		{
			var list=   ChangeDormitorybaseRepository.GetAll().Where(c=>c.IsDel==0).ToList();


			if (!string.IsNullOrEmpty(startDate))
			{
				list = list.Where(c => c.ChangedormitoryDate >= DateTime.Parse(startDate)).ToList();
			}

			if (!string.IsNullOrEmpty(endDate))
			{
				list = list.Where(c => c.ChangedormitoryDate <= DateTime.Parse(endDate)).ToList();
			}

			if (!string.IsNullOrEmpty(OverBit))
			{
				list = list.Where(c => c.OverBit .Contains(OverBit)).ToList();
			}

			if (ChangedormitoryType!= 0)
			{
				list = list.Where(c => c.ChangedormitoryType == ChangedormitoryType).ToList();
			}

			if (!string.IsNullOrEmpty(outDrom))
			{
				list = list.Where(c => c.TransferOutDormitory == outDrom).ToList();
			}

			if (!string.IsNullOrEmpty(outField))
			{
				list = list.Where(c => c.RollOutField   == outField).ToList();
			}

			if (inDrom!= 0)
			{
				list = list.Where(c => c.TransferToDormitory == inDrom).ToList();
			}

			if (inField!= 0)
			{
				list = list.Where(c => c.DriveField == inField).ToList();
			}
			var result = new PageOutput<SheepChangeDormitoryOutput>()
			{
				Total = list.Count(),
				PageSize=pageSize,

			};

			var entity = list.OrderByDescending(c => c.SheepChangedormitoryId).Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();

		



			var changedormitordto = mapper.Map<List<SheepChangeDormitoryOutput>>(entity);
			result.Data = changedormitordto;
			return result;
		}

	
	    /// <summary>
		/// 羊只转舍添加
		/// </summary>
		/// <param name="model"></param>
		/// <returns></returns>
		public async Task<int> AddChangeDormitory(List<SheepChangeDormitory> modelList)
		{

		 foreach (var model in modelList)
			{

				Random random = new Random();
                model.AddTime=DateTime.Now;
            //单据号生成
            model.DocumentNumber = "No." + Yitter.IdGenerator.YitIdHelper.NextId().ToString() + model.SheepChangedormitoryId.ToString()+ random.Next(1000, 9999).ToString();
			//流水号生成
			model.SerialNumber=DateTime.Now.ToString("yyyyMMddHHmmss") + model.SheepChangedormitoryId.ToString()+random.Next(1000, 9999).ToString();
			var result=  ChangeDormitorybaseRepository.Add(model);
			//同步修改羊只档案当前栋舍

			if (result > 0)
			{
              var sheepRecord = SheepRecordbaseRepository.GetAll().FirstOrDefault(c=>c.OverBit.Contains(model.OverBit));
				//查询结果非空

				if (sheepRecord != null)
				{
					sheepRecord.BuildingName = BuildingbaseRepository.GetAll().FirstOrDefault(c => c.BuildingManagementId == model.TransferToDormitory).BuildingName;

					sheepRecord.SheepFieldName = SheepFieldbaseRepository.GetAll().FirstOrDefault(c => c.SheepFieldId == model.DriveField).SheepFieldName;

				SheepRecordbaseRepository.Update(sheepRecord);

                }
            }

            

            }
		 return 1;
        }


        /// <summary>
        /// 羊只转舍删除
        /// </summary>
        /// <param name="ChangeId"></param>
        /// <returns></returns>
        public async Task< int> DeleteChangeDormitory(List<int> ChangeId)
		{
			//var model = ChangeDormitorybaseRepository.GetValue(ChangeId);

			var model = ChangeDormitorybaseRepository.GetAll().Where(c => c.IsDel == 0 && ChangeId.Contains(c.SheepChangedormitoryId)).ToList();




            if (model!= null)
			{
				foreach (var item in model)
				{
                    item.IsDel = 1;
                    item.DelTime = DateTime.Now;
                    ChangeDormitorybaseRepository.Update(item);
                }







				return 1;//删除成功

               
            }

			 return -1;//删除失败


		}
		/// <summary>
		/// 羊只转舍审核
		/// </summary>
		/// <param name="ChangeId"></param>
		/// <param name="Status"></param>
		/// <returns></returns>
		public async Task<int> UpdateChangeDormitoryState(int ChangeId, int Status)
		{
			var model = ChangeDormitorybaseRepository.GetValue(ChangeId);


			if (model == null)
			{
				return 0;//审核失败
			}
			model .AuditTime = DateTime.Now;
			model.ChangeState = Status;
			return ChangeDormitorybaseRepository.Update(model);
		}


		/// <summary>
		/// 羊只转舍详情-反填
		/// </summary>
		/// <param name="ChangeDormId"></param>
		/// <returns></returns>
		public async Task<SheepChangeDormitoryOutput> GetChangeDormitoryById(int ChangeDormId)
		{
			var list = ChangeDormitorybaseRepository.GetAll().FirstOrDefault(c => c.IsDel == 0 && c.SheepChangedormitoryId == ChangeDormId);
			return mapper.Map<SheepChangeDormitoryOutput>(list);


        }

		//羊只转舍修改 
		public async Task<int> UpdateChangeDormitory(SheepChangeDormitory model)
		{

            model.UpdateTime=DateTime.Now;

            var result =  ChangeDormitorybaseRepository.Update(model);
			return result;
		}

	
	
	}
}
